package com.rc.evcharger.service;

import com.rc.evcharger.common.redis.RedisDao;
import com.rc.evcharger.common.utils.DataUtil;
import com.rc.evcharger.mapper.member.MemberInfoMapper;
import com.rc.evcharger.mapper.order.OrderCommentMapper;
import com.rc.evcharger.mapper.order.OrderInfoMapper;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.model.member.MemberInfo;
import com.rc.evcharger.model.order.OrderComment;
import com.rc.evcharger.model.order.OrderInfo;
import com.rc.evcharger.redis.RedisService;
import com.rc.evcharger.service.elec.ElecGunService;
import com.rc.evcharger.service.elec.ElecPileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class CurrDataServiceImpl implements CurrDataService {
    Logger logger = LoggerFactory.getLogger(CurrDataServiceImpl.class);

    @Autowired
    private RedisService redisService;

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderCommentMapper orderCommentMapper;

    @Autowired
    private RedisDao redisDao;

    /**
     * 根据用户桩id,用户id,枪号，数据项编码读取当前数据（单个）
     */
    public String getCurrData(Long pileId, Long memberId, String gunNum, String code) {
        ElecPile pile = elecPileService.selectByPrimaryKey(pileId);

        //根据枪和会员获取最新一条订单
        ElecGun elecGun = elecGunService.validGun(pile, gunNum);
        OrderComment orderComment = orderCommentMapper.selectNewOrderByMemberIdAndGunId(memberId, elecGun.getElecGunId());


        String key = DataUtil.getCurrDataKey(pile.getPileRtua(), gunNum, code, orderComment.getOrderNum());
        String valueStr = redisService.getRedis(key);

        //旧key的值
        if (valueStr == null) {
            MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberId);
            String oldKey = DataUtil.getCurrDataKey(pile.getPileRtua(), gunNum, code, memberInfo.getMobile());
            valueStr = redisService.getRedis(oldKey);
        }


        if (valueStr == null || valueStr.equals("FF FF")) {// 代表数据不存在
            return null;
        }
        Class type = DataUtil.getValueType(code);
        if (code.equals("40 C8")) {
            return valueStr;
        } else if (type.equals(BigDecimal.class)) {
            return valueStr;
        }
        return valueStr;
    }

    /**
     * 根据用户桩id,用户id,枪号，数据项编码读取当前数据（多个）
     */
    @Override
    public Map<String, Object> getCurrData(Long pileId, Long memberId, String gunNum, String... codeKey) {
        String[] codes = DataUtil.turnCode(codeKey);
        Map<String, Object> result = new HashMap<>();
        ElecPile pile = elecPileService.selectByPrimaryKey(pileId);

        //根据枪和会员获取最新一条订单
        ElecGun elecGun = elecGunService.validGun(pile, gunNum);
        OrderInfo orderInfo = orderInfoMapper.selectNewOrderByMemberIdAndGunId(memberId, elecGun.getElecGunId());

        String key = null;
        Object value = null;
        Class type = null;

        for (int i = 0; i < codes.length; i++) {

            //枪状态C804在redis中没有带cardNo保存
            if (!codes[i].equals("40 C8")) {
                key = DataUtil.getCurrDataKey(pile.getPileRtua(), gunNum, codes[i], orderInfo.getOrderNum());
            } else {
                key = DataUtil.getCurrDataKey(pile.getPileRtua(), gunNum, codes[i]);
            }
            String valueStr = redisService.getRedis(key);

            //获取旧key的值
            if (valueStr == null || valueStr.equals("FF FF")) {
                if (!codes[i].equals("40 C8")) {
                    MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberId);
                    key = DataUtil.getCurrDataKey(pile.getPileRtua(), gunNum, codes[i], memberInfo.getMobile());
                } else {
                    key = DataUtil.getCurrDataKey(pile.getPileRtua(), gunNum, codes[i]);
                }
                valueStr = redisService.getRedis(key);
            }


            if (valueStr == null || valueStr.equals("FF FF")) { // 代表数据不存在
                continue;
            }
            type = DataUtil.getValueType(codes[i]);
            if (codes[i].equals("40 C8")) {
                value = Integer.parseInt(valueStr);
            }
            if (type.equals(BigDecimal.class)) {
                value = new BigDecimal(valueStr);
            } else {
                value = valueStr;
            }
            result.put(codeKey[i], value);
        }
        //打印返回日志
        String resultLog = "会员ID:" + memberId + " 桩编号:" + pile.getPileNo() + " gunNum:" + gunNum;
        for (String s : result.keySet()) {
            resultLog += " " + s + ":" + result.get(s);
        }
        logger.warn(resultLog);

        return result;
    }

    @Override
    public Map<String, Object> getCurrSoc(Long pileId, String gunNum, String... codeKey) {
        String[] codes = DataUtil.turnCode(codeKey);
        Map<String, Object> result = new HashMap<>();
        ElecPile pile = elecPileService.selectByPrimaryKey(pileId);
        ElecGun elecGun = elecGunService.validGun(pile, gunNum);
        OrderInfo orderInfo = orderInfoMapper.selectByPileIdAndGunId(pileId, elecGun.getElecGunId());

        Object value = null;
        String key = DataUtil.getCurrDataKey(pile.getPileRtua(), gunNum, codes[0], orderInfo.getOrderNum());
        //List<String> keys = (List<String>) redisDao.keys(key + "*");
        //for (String k : keys) {
        //    value = redisService.getRedis(k);
        //}
        value = redisDao.getRedis(key);

        //获取旧soc
        if (value == null) {
            MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(orderInfo.getMemberId());
            key = DataUtil.getCurrDataKey(pile.getPileRtua(), gunNum, codes[0], memberInfo.getMobile());
            value = redisDao.getRedis(key);
        }

        result.put(codeKey[0], value);
        return result;
    }

    //@Override
    //public ResponseBean member(Long memberId) {
    //    try {
    //        Member member = memberMapper.selectByPrimaryKey(memberId);
    //        PlatformUser plat = platformUserService.getMapper().selectByPrimaryKey(1l);
    //
    //        member.setPfUser(plat.getId());
    //        plat.setMember(member.getId());
    //        logger.error("一对一打印member.setPfUser()=" + member.getPfUser() + " 一对一打印plat.getMember()=" + plat.getMember());
    //
    //        platformUserService.getMapper().insertSelective(plat);
    //        memberMapper.insertSelective(member);
    //
    //        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, member);
    //    } catch (Exception e) {
    //        logger.error(e.getMessage(), e);
    //        return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, "fail");
    //    }
    //}
}
